package org.middleware.common.AuthenticationToken;

import org.middleware.entity.system.SysUsers;
import org.middleware.service.system.SysUsersService;
import org.middleware.utils.JwtTokenUtil;
import org.middleware.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SysUsersService usersService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查方法是否有@RequireLogin注解
        RequireLogin requireLogin = method.getAnnotation(RequireLogin.class);
        if (requireLogin == null) {
            // 检查类是否有@RequireLogin注解
            requireLogin = method.getDeclaringClass().getAnnotation(RequireLogin.class);
        }

        // 如果没有@RequireLogin注解，直接通过
        if (requireLogin == null) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        String name = jwtTokenUtil.getUsernameFromToken(token);

        // 验证token，从redis查询token 是否存在
        if (token == null || !jwtTokenUtil.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            if (name == null || name.isEmpty()) {
                response.getWriter().write("{\"code\": 401, \"message\": \"会话信息异常，请清除缓存重新登录\"}");
                return false;
            }
            String tokenKey = name + "-token";
            Object redis = redisUtil.get(tokenKey);
            if (redis == null) {
                response.getWriter().write("{\"code\": 401, \"message\": \"会话已过期，请求重新登录\"}");
                return false;
            }
            if (token.equals(redis.toString())) {
                response.getWriter().write("{\"code\": 401, \"message\": \"token验证失败\"}");
                return false;
            }

        }

        // 检查token是否过期
//        if (jwtUtil.isTokenExpired(token)) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write("{\"code\": 401, \"message\": \"登录已过期，请重新登录\"}");
//            return false;
//        }

        // 将用户信息存入request，方便后续使用
        String userName = jwtTokenUtil.getUsernameFromToken(token);
        SysUsers user = usersService.getUserByName(name);
        request.setAttribute("userId", user.getId());
        request.setAttribute("userName", userName);
        request.setAttribute("isAdmin", user.getIsSuperAdmin());

        return true;
    }
}
